<?php

namespace app\index\traits;

use app\common\model\Member;
use app\index\dao\ConsultingDao;
use ShidianUtil\Utils\TimeUtil;
use think\exception\ValidateException;
use think\facade\Config;

/**
 * 咨询
 * Trait ConsultingTrait
 * @package app\index\traits
 */
trait ConsultingTrait
{

    /**
     * 用户才能发起咨询
     * @param Member $user
     * @return void
     */
    private function checkConsultingCreator(Member $user): void
    {

        // 用户才能发起咨询
        if ($user->type == 0) {
            return;
        }

        $names = [0 => '用户', 1 => '律师', 2 => '客服'];
        $name = $names[$user->type] ?? '您';
        throw new ValidateException($name . '不能发起咨询');
    }

    private function checkConsultingLawyer(Member $user, $lawyerId): void
    {
        $lawyer = Member::where('id', $lawyerId)->where('type', '1')->find();

        if (is_null($lawyer)) {
            throw new ValidateException('该律师不存在或已被删除');
        }

        if($lawyer->muted == 1){
            throw new ValidateException('该律师已经禁言');
        }

        if($lawyer->status != 1){
            throw new ValidateException('该律师已被封禁');
        }

    }

    /**
     * 检查咨询创建是否过于频繁
     * @return void
     */
    private function checkConsultingTimes(Member $member): void
    {
        $memberId = $member->id;
        $phone = $member->phone;
        // 从该时间开始统计
        $day_time = TimeUtil::stamp(TimeUtil::DAY);
        // 一天内可以创建的咨询数量
        $maxTimes = 100;

        // 测试账号 & 开发者账号
        if (in_array($phone, Config::get('member.testAccount', [])) || in_array($phone, Config::get('member.developerAccount', []))) {
            return;
        }

        // 今天创建咨询次数
        $count = $this->getConsultingDao()->countConsultingByDay($memberId, $day_time);

        // 限制一天内可以创建的咨询数量
        if ($count > $maxTimes) {
            throw new ValidateException('您今天进行太多咨询了，请休息一下');
        }

    }

    private function getConsultingDao(): ConsultingDao
    {
        return app(ConsultingDao::class);
    }
}